﻿/*
   　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class Basic_Boar_sys_Genealogy
    {
        public static BLL.Basic_Boar_sys_Genealogy category = new BLL.Basic_Boar_sys_Genealogy();
        public static Model.Basic_Boar_sys_Genealogy model = new Model.Basic_Boar_sys_Genealogy();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public Basic_Boar_sys_Genealogy()
        {
        }

        public Basic_Boar_sys_Genealogy(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string save()
        {
            model.ParFatherBoarId = PageValidate.InputText(request["T_fbh_val"], 50);
            model.ParMotherBoarId = PageValidate.InputText(request["T_mbh_val"], 250);
            model.boarId_origin = (PageValidate.InputText(request["oid"], 250));
            model.boarId = PageValidate.InputText(request["bid"], 250);
            model.levels = StringPlus.str2int(request["level"]);
            string id = PageValidate.InputText(request["id"], 50); 
            if (PageValidate.checkID(id))
            {
                 model.id = id; 
                category.Update(model);
 

            }

            else
            {
                string sqlwhere = " 1=1 ";
                 sqlwhere += " AND    boarId_origin = '" + model.boarId_origin + "' AND ( boarId = '" + model.boarId + "' OR ParFatherBoarId='" + model.boarId + "' OR ParMotherBoarId='" + model.boarId + "') ";
                //  if (model.levels == 2) sqlwhere += " AND   boarId_origin = '" + model.boarId_origin + "' AND (ParFatherBoarId='"+model.boarId+ "' OR ParMotherBoarId='" + model.boarId + "' )  levels=" + model.levels + "";
                //  if (model.levels == 3) sqlwhere += " AND   boarId_origin = '" + model.boarId_origin + "' AND (ParFatherBoarId='" + model.boarId + "' OR ParMotherBoarId='" + model.boarId + "' )  AND  levels=" + model.levels + "";
                //DataSet ds = category.GetList(sqlwhere);
                //if (ds.Tables[0].Rows.Count > 1)
                //{
                //    XhdResult.Error( "已经选了重复!").ToString();
                //}
                //else
                {
                    model.id = Guid.NewGuid().ToString();
                    //model.cr = emp_name;
                    //model.create_time = DateTime.Now;
                    category.Add(model);
                }

            }
            return XhdResult.Success().ToString();
        }

        public string save2()
        {
            model.ParFatherBoarId = PageValidate.InputText(request["T_fbh"], 50);
            model.ParF_name = PageValidate.InputText(request["T_fname"], 50);
            model.ParF_barcode = PageValidate.InputText(request["T_fbh"], 50);
            model.ParF_remark = PageValidate.InputText(request["T_fbz"], 250);
            model.ParMotherBoarId = PageValidate.InputText(request["T_mbh"], 250);
            model.ParM_barcode= PageValidate.InputText(request["T_mbh"], 50);
            model.ParM_name = PageValidate.InputText(request["T_mname"], 250);
            model.ParM_remark = PageValidate.InputText(request["T_mbz"], 250);
            model.boarId_origin = (PageValidate.InputText(request["oid"], 250));
            model.boarId = PageValidate.InputText(request["bid"], 250);
            model.levels = StringPlus.str2int(request["level"]);
            string id = PageValidate.InputText(request["id"], 50);
            if (PageValidate.checkID(id))
            {
                model.id = id;
                category.Update(model);


            }

            else
            {
                string sqlwhere = " 1=1 ";
                sqlwhere += " AND    boarId_origin = '" + model.boarId_origin + "' AND ( boarId = '" + model.boarId + "' OR ParFatherBoarId='" + model.boarId + "' OR ParMotherBoarId='" + model.boarId + "') ";
                //  if (model.levels == 2) sqlwhere += " AND   boarId_origin = '" + model.boarId_origin + "' AND (ParFatherBoarId='"+model.boarId+ "' OR ParMotherBoarId='" + model.boarId + "' )  levels=" + model.levels + "";
                //  if (model.levels == 3) sqlwhere += " AND   boarId_origin = '" + model.boarId_origin + "' AND (ParFatherBoarId='" + model.boarId + "' OR ParMotherBoarId='" + model.boarId + "' )  AND  levels=" + model.levels + "";
                //DataSet ds = category.GetList(sqlwhere);
                //if (ds.Tables[0].Rows.Count > 1)
                //{
                //    XhdResult.Error( "已经选了重复!").ToString();
                //}
                //else
                {
                    model.id = Guid.NewGuid().ToString();
                    //model.cr = emp_name;
                    //model.create_time = DateTime.Now;
                    category.Add(model);
                }

            }
            return XhdResult.Success().ToString();
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            //if (!string.IsNullOrEmpty(request["categoryid"]))
            //    serchtxt += $" and category_id='{PageValidate.InputText(request["categoryid"], 50)}'";

            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";

            //权限
            DataSet ds = category.GetList2(request["bid"], request["pid"],StringPlus.str2int( request["level"]));

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], "2");
            return (dt);

        }

        public string tree(string bid)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(" SELECT * FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.boarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' ");
            sb.AppendLine("   ");

            //sb.AppendLine(" WHERE A.boarId='"+bid+"'  ");


            DataSet ds = DBUtility.DbHelperSQL.Query(sb.ToString());
            var str = new StringBuilder();
          
            str.Append(GetTreeString(bid,ds.Tables[0]));  
            return str.ToString();
        }

        public string tree2(string bid)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(" SELECT * FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.boarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' ");
            sb.AppendLine("   ");

            //sb.AppendLine(" WHERE A.boarId='"+bid+"'  ");


            DataSet ds = DBUtility.DbHelperSQL.Query(sb.ToString());
            var str = new StringBuilder();

            str.Append(GetTreeString2(bid, ds.Tables[0],"1"));
            return str.ToString();
        }

        public string form(string oid,string bid,string level,string id)
        {
            if (!PageValidate.checkID(oid)) return "{}";
            oid = PageValidate.InputText(oid, 50);
            DataSet ds = category.GeForm(oid, bid, StringPlus.str2int(level),id);
            return DataToJson.DataToJSON(ds);

        }

        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return "false";
            id = PageValidate.InputText(id, 50);
          

            bool isdel = category.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误！").ToString();

            //日志
            string EventType = "产品类别删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = "";

            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();

        }

        private static string GetTreeString2(string bid, DataTable table, string FM = "1")
        {
            ArrayList FathersArrayList = new ArrayList();
            ArrayList MothersArrayList = new ArrayList();

            string result = "";

            var str = new StringBuilder();
            foreach (DataRow row in table.Select($" levels=1 "))
            {
                string boarId = row["boarId"].ToString();
                string product_name = row["product_name"].ToString();
                string barcode = row["barcode"].ToString();
                string levels = row["levels"].ToString();
                List<object> list2 = new List<object>();
                List<object> list3 = new List<object>();
                list2 = GetStringLevel2(bid, row["boarId"].ToString(), row["boarId"].ToString(), 1);

                object level_1 = new
                {
                    orderId = boarId,
                    text = barcode,
                    amount = product_name,
                    isExpand = true,
                    hasHumanholding = true,
                    hasChildren = true,
                    name = "origin",
                    children = list2
                };
                // str.Append("{\"orderId\":\"" + boarId + "\",\"text\":\"" + barcode + "\",\"amount\":\"" + product_name + "\",\"isExpand\":true,\"hasHumanholding\":true,\"name\":\"" + FM + "\",");
                object downward = new
                {
                    downward = level_1
                };
                result = StringToJson.ObjectToJson(downward);
            }

            return result;
        }
        private static List<object> GetStringLevel2(string bid,  string pid,string mid, int level)
        {
            List<object> list = new List<object>();
            List<object> list2 = new List<object>();
            StringBuilder sb = new StringBuilder(); 
            sb.AppendLine("    ");
            sb.AppendLine(" SELECT ParFatherBoarId,ParMotherBoarId, ParFatherBoarId AS id,ParF_barcode AS barcode,ParF_name AS name ,ParF_remark AS remark,levels  ,'M' as sex   ");
            sb.AppendLine(" FROM dbo.Basic_Boar_sys_Genealogy A ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=" + level + "  AND boarId='" + pid + "'");
            sb.AppendLine(" UNION ALL	  ");
            sb.AppendLine(" SELECT ParFatherBoarId,ParMotherBoarId, ParMotherBoarId AS id,ParM_barcode AS barcode,ParM_name AS name ,ParM_remark AS remark,levels,'F' as sex   ");
            sb.AppendLine(" FROM dbo.Basic_Boar_sys_Genealogy A ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=" + level + "  AND boarId='" + mid + "'");
             

            DataSet ds = DBUtility.DbHelperSQL.Query(sb.ToString()); 
            foreach (DataRow row_3 in ds.Tables[0].Rows) 
            {
                list = GetStringLevel2(bid, row_3["id"].ToString(), row_3["id"].ToString(), level+1); 
                object level_3 = new
                {
                    orderId = row_3["id"].ToString(),
                    text = row_3["barcode"].ToString(),
                    amount = row_3["name"].ToString(),
                    isExpand = true,
                    hasHumanholding = true,
                    hasChildren = true,
                    name = row_3["sex"].ToString(),
                    ratio = row_3["levels"].ToString(),
                    children = list
                };

                list2.Add(level_3);
                
            }
            return list2;
        }


        private static string GetTreeString(string bid, DataTable table,string FM="origin")
        {
            ArrayList FathersArrayList = new ArrayList();
            ArrayList MothersArrayList = new ArrayList();

            string result = "";
           
                var str = new StringBuilder();  
            foreach (DataRow row in table.Select($" levels=1"))
            {
                string boarId =  row["boarId"].ToString();
                string product_name = row["product_name"].ToString();
                string barcode = row["barcode"].ToString();
                string levels = row["levels"].ToString();
                List<object> list2 = new List<object>();
                List<object> list3 = new List<object>();
                list2= GetStringLevel3(bid, row["ParFatherBoarId"].ToString(), row["ParMotherBoarId"].ToString());
               
                object level_1 = new {
                    orderId=boarId,
                    text=barcode,
                    amount=product_name,
                    isExpand=true,
                    hasHumanholding=true,
                    hasChildren=true,
                    name = "origin",
                    children=list2
                };
                // str.Append("{\"orderId\":\"" + boarId + "\",\"text\":\"" + barcode + "\",\"amount\":\"" + product_name + "\",\"isExpand\":true,\"hasHumanholding\":true,\"name\":\"" + FM + "\",");
                object downward = new
                {
                    downward = level_1
                };
                result = StringToJson.ObjectToJson(downward);
            }
         
            return result;
        }

      
        private static List<object> GetStringLevel3(string bid, string pid, string mid)
        {
            List<object> list = new List<object>();
            List<object> list2 = new List<object>();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(" SELECT  A.*  ");
            sb.AppendLine(" ,boarId,barcode,product_name,3  as levels,'M' as sex ");
            sb.AppendLine("  FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.ParFatherBoarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=2  AND boarId='" + pid + "'");
            sb.AppendLine("   UNION ALL	   ");
            sb.AppendLine("  SELECT  A.*  ");
            sb.AppendLine(" ,boarId,barcode,product_name,3 as levels ,'F' as sex ");
            sb.AppendLine("  FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.ParMotherBoarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=2   AND boarId='" + mid + "'");

            DataSet ds = DBUtility.DbHelperSQL.Query(sb.ToString()); 
            foreach (DataRow row_3 in ds.Tables[0].Rows)
            { 
                    list = GetStringLevel4(bid, row_3["ParFatherBoarId"].ToString(), row_3["ParMotherBoarId"].ToString()); 
                object level_3 = new
                {
                    orderId = row_3["boarId"].ToString(),
                    text = row_3["barcode"].ToString(),
                    amount = row_3["product_name"].ToString(),
                    isExpand = true,
                    hasHumanholding = true,
                    hasChildren = true,
                    name = row_3["sex"].ToString(),
                    ratio = row_3["levels"].ToString(),
                    children = list
                };

                list2.Add(level_3);
            }
            return list2;
        }
        private static List<object> GetStringLevel4(string bid, string pid, string mid)
        {
            List<object> list = new List<object>();
            List<object> list2 = new List<object>();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(" SELECT  A.*  ");
            sb.AppendLine(" ,boarId,barcode,product_name,3  as levels,'M' as sex ");
            sb.AppendLine("  FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.ParFatherBoarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=3  AND boarId='" + pid + "'");
            sb.AppendLine("   UNION ALL	   ");
            sb.AppendLine("  SELECT  A.*  ");
            sb.AppendLine(" ,boarId,barcode,product_name,3 as levels ,'F' as sex ");
            sb.AppendLine("  FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.ParMotherBoarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=3   AND boarId='" + mid + "'");

            DataSet ds = DBUtility.DbHelperSQL.Query(sb.ToString());
            foreach (DataRow row_3 in ds.Tables[0].Rows)
            {
                list = GetStringLevel5(bid, row_3["ParFatherBoarId"].ToString(), row_3["ParMotherBoarId"].ToString());
                object level_3 = new
                {
                    orderId = row_3["boarId"].ToString(),
                    text = row_3["barcode"].ToString(),
                    amount = row_3["product_name"].ToString(),
                    isExpand = true,
                    hasHumanholding = true,
                    hasChildren = true,
                    name = row_3["sex"].ToString(),
                    ratio = row_3["levels"].ToString(),
                    children = list
                };

                list2.Add(level_3);
            }
            return list2;
        }

        private static List<object> GetStringLevel5(string bid,string pid,string mid)
        {
            List<object> list  = new List<object>();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(" SELECT  A.*  ");
            sb.AppendLine(" ,boarId,barcode,product_name,4 as levels,'M' as sex ");
            sb.AppendLine("  FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.ParFatherBoarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='"+bid+ "' AND A.levels=3  AND ParFatherBoarId='"+ pid + "' ");
            sb.AppendLine("   UNION ALL	   ");
            sb.AppendLine("  SELECT  A.*  ");
            sb.AppendLine(" ,boarId,barcode,product_name,4 as levels ,'F' as sex ");
            sb.AppendLine("  FROM dbo.Basic_Boar_sys_Genealogy A  ");
            sb.AppendLine(" INNER JOIN  dbo.Basic_boar B ON	 A.ParMotherBoarId=B.id    ");
            sb.AppendLine("  where A.boarId_origin='" + bid + "' AND A.levels=3  AND ParMotherBoarId='" + mid + "' ");

            DataSet ds = DBUtility.DbHelperSQL.Query(sb.ToString());
            foreach (DataRow row_4 in ds.Tables[0].Rows)
            {
                object level_4 = new
                {
                    orderId = row_4["boarId"].ToString(),
                    text = row_4["barcode"].ToString(),
                    amount = row_4["product_name"].ToString(),
                    isExpand = true,
                    hasHumanholding = true,
                    ratio ="4",
                    name = row_4["sex"].ToString(), 
                };
                list.Add(level_4);
            }
            return list;
        }

    }
}
